// 链表来实现栈
// es5 没有class 关键字
// es6 有了class 关键字
class ListNode { 
    constructor(val) { 
        this.val = val; 
        this.next = null; // 离散存储
    }
}

class LinkedListStack {
  // 私有的 只能在内部使用， 封装实现的细节， 保护类不被随意修改
  // 栈顶指针
  #stackPeek;
  // 栈大小
  #size= 0;
  constructor() { 
    // 初始化栈顶指针为null
      this.#stackPeek = null; 
  }
push(num) {
    const node = new ListNode(num);
    node.next = this.#stackPeek;
    this.#stackPeek = node;
    this.#size++;
}
peek() {
    if(!this.#stackPeek) throw new Error('栈为空');
    return this.#stackPeek.val;
}
pop() {
    const num = this.peek();
    this.#stackPeek = this.#stackPeek.next;
    this.#size--;
    return num;
}
// get 属性 // 方便外部访问
get size() {
    return this.#size;
}
isEmpty() {
    return this.#size === 0;
}
toArray() {
    // const arr = [];
    // let cur = this.#stackPeek;
    // while(cur) {
    //     arr.push(cur.val);
    //     cur = cur.next;
    // }
    // return arr.reverse();
    let node = this.#stackPeek;
    const res = new Array(this.size); // 创建一个「指定长度（length）的空数组」
    for(let i = this.#size - 1; i >= 0; i--) {
        res[i] = node.val;
        node = node.next;
    }
    return res;
}
}
const stack = new LinkedListStack();
console.log(stack.size);